﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using CodeFactory.IDAL;
using CodeFactory.Library;
using CodeFactory.Library.CodeRunner;
using CodeFactory.Library.Config;
using CodeFactory.Library.Language;

namespace CodeFactory.UI
{
    public partial class MainForm : Form
    {
        private static int mainWidth;
        private static int mainHeight;

        private int startWidth;
        private int startHeigth;
        private string path;
        private Thread createThread;

        private List<string> tableList;

        private IDataAdapter dataAdapter;
        private CodeCreater codeCreater;
        private Runner nameRunner;

        private ConnectForm connectForm;
        private CreateSettingForm createSettingForm;
        private ProgressForm progressForm;
        private SystemSettingForm systemSettingForm;
        private LanguageForm languageForm;
        private AboutForm aboutForm;

        public Thread CreateThread
        {
            get { return this.createThread; }
        }

        public MainForm()
        {
            InitializeComponent();
            //添加事件
            this.Resize += new EventHandler(MainForm_Resize);
            this.exitToolStripMenuItem.Click += this.MainForm_Exit;
            this.saveToolStripMenuItem.Click += this.MainForm_Save;
            this.saveAllToolStripMenuItem.Click += this.MainForm_SaveAll;
            this.connectToolStripMenuItem.Click += this.MainForm_Connect;
            this.breakOffToolStripMenuItem.Click += this.MainForm_BreakOff;
            this.createSettingToolStripMenuItem.Click += this.MainForm_CreateSetting;
            this.systemSettingToolStripMenuItem.Click += this.MainForm_SystemSetting;
            this.languageToolStripMenuItem.Click += this.MainForm_LanguageSetting;
            this.helpToolStripMenuItem1.Click += this.MainForm_Help;
            this.onlineToolStripMenuItem.Click += this.MainForm_Online;
            this.publicToolStripMenuItem.Click += this.MainForm_PublicPage;
            this.aboutToolStripMenuItem.Click += this.MainForm_About;
            this.toolbar_connect.Click += this.MainForm_Connect;
            this.toolbar_breakoff.Click += this.MainForm_BreakOff;
            this.toolbar_save.Click += this.MainForm_Save;
            this.toolbar_saveall.Click += this.MainForm_SaveAll;
            this.toolbar_creatingsetting.Click += this.MainForm_CreateSetting;
            this.toolbar_systemsetting.Click += this.MainForm_SystemSetting;
            this.toolbar_language.Click += this.MainForm_LanguageSetting;
            this.toolbar_help.Click += this.MainForm_Help;
            this.toolbar_online.Click += this.MainForm_Online;
            this.toolbar_publicpage.Click += this.MainForm_PublicPage;
            this.toolbar_about.Click += this.MainForm_About;
            this.tableView.AfterSelect += this.MainForm_SelectTable;
            //添加事件完成
            //初始化子窗口对象
            this.connectForm = new ConnectForm();
            this.createSettingForm = new CreateSettingForm();
            this.progressForm = new ProgressForm();
            this.progressForm.Owner = this;
            this.systemSettingForm = new SystemSettingForm();
            this.languageForm = new LanguageForm();
            this.aboutForm = new AboutForm();
            //初始化子窗口对象完成
            //初始化功能对象
            this.path = string.Empty;
            this.dataAdapter = null;
            this.columnView.View = View.Details;
            this.columnView.MultiSelect = false;
            this.columnView.FullRowSelect = true;
            this.codeCreater = new CodeCreater();
            this.nameRunner = new Runner();
            this.nameRunner.CodeInfo = ConfigManager.Info.SysEncoder;
            this.codeCreater.NameRunner = nameRunner;
            this.codeCreater.FinishOneColumn += this.progressForm.UpdateCreateMessage;
            this.codeCreater.FinishOneTable += this.OnFinishOneTable;
            //初始化功能对象完成
            this.StartPosition = FormStartPosition.CenterScreen;
            mainWidth = Screen.PrimaryScreen.WorkingArea.Width;
            mainHeight = Screen.PrimaryScreen.WorkingArea.Height;
            this.startWidth = (int) ( mainWidth / 1.5);
            this.startHeigth = (this.startWidth * mainHeight) / mainWidth;
            this.Width = this.startWidth;
            this.Height = this.startHeigth;
            this.mainContainer.Width = this.Width;
            this.mainContainer.Height = this.Height - this.mainMenu.Height - this.mainTools.Height - this.mainStatus.Height -30;
            this.tableView.Width = this.mainContainer.Panel1.Width;
            this.tableView.Height = this.mainContainer.Panel1.Height + 1;
            this.columnView.Width = this.mainContainer.Panel2.Width;
            this.columnView.Height = this.mainContainer.Panel2.Height + 1;
            this.mainContainer.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            this.tableView.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            this.columnView.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            //初始化
            try
            {
                this.InitCommonText();
                this.InitTableView();
                this.InitColumnViewTitle();
                this.InitButtonState();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "CodeFactory System Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                System.Environment.Exit(-1);
            }
        }

        void MainForm_Resize(object sender, EventArgs e)
        {
            //throw new Exception("The method or operation is not implemented.");
            this.InitColumnViewTitle();
        }

        private void InitCommonText()
        {
            this.Text = LanguageManager.StringManager["MainForm_Title"];
            this.fileToolStripMenuItem.Text = LanguageManager.StringManager["Menu_File"];
            this.saveToolStripMenuItem.Text = LanguageManager.StringManager["Menu_File_Save"];
            this.saveAllToolStripMenuItem.Text = LanguageManager.StringManager["Menu_File_SaveAll"];
            this.exitToolStripMenuItem.Text = LanguageManager.StringManager["Menu_File_Exit"];
            this.operationToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Operation"];
            this.connectToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Operation_Connect"];
            this.breakOffToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Operation_BreakOff"];
            this.systemToolStripMenuItem.Text = LanguageManager.StringManager["Menu_System"];
            this.createSettingToolStripMenuItem.Text = LanguageManager.StringManager["Menu_System_CreatingSetting"];
            this.languageToolStripMenuItem.Text = LanguageManager.StringManager["Menu_System_Language"];
            this.systemSettingToolStripMenuItem.Text = LanguageManager.StringManager["Menu_System_SystemSetting"];
            this.helpToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Help"];
            this.helpToolStripMenuItem1.Text = LanguageManager.StringManager["Menu_Help_Help"];
            this.onlineToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Help_Online"];
            this.publicToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Help_PublicPage"];
            this.aboutToolStripMenuItem.Text = LanguageManager.StringManager["Menu_Help_About"];
            this.toolbar_save.Text = LanguageManager.StringManager["Toolbar_Save"];
            this.toolbar_saveall.Text = LanguageManager.StringManager["Toolbar_SaveAll"];
            this.toolbar_connect.Text = LanguageManager.StringManager["Toolbar_Connect"];
            this.toolbar_breakoff.Text = LanguageManager.StringManager["Toolbar_BreakOff"];
            this.toolbar_creatingsetting.Text = LanguageManager.StringManager["Toolbar_CreatingSetting"];
            this.toolbar_systemsetting.Text = LanguageManager.StringManager["Tollbar_SystemSetting"];
            this.toolbar_language.Text = LanguageManager.StringManager["Toolbar_Language"];
            this.toolbar_help.Text = LanguageManager.StringManager["Toolbar_Help"];
            this.toolbar_online.Text = LanguageManager.StringManager["Toolbar_Online"];
            this.toolbar_publicpage.Text = LanguageManager.StringManager["Toolbar_PublicPage"];
            this.toolbar_about.Text = LanguageManager.StringManager["Toolbar_About"];
        }

        private void InitColumnViewTitle()
        {

            this.columnView.Columns.Clear();
            ColumnHeader head = new ColumnHeader();
            head.Name = "columnName";
            head.Text = LanguageManager.StringManager["ColumnHeader_SqlName"];
            head.Width = (int)(this.columnView.Width * 0.3);
            this.columnView.Columns.Add(head);
            head = new ColumnHeader();
            head.Name = "columnType";
            head.Text = LanguageManager.StringManager["ColumnHeader_SqlType"];
            head.Width = (int)(this.columnView.Width * 0.2);
            this.columnView.Columns.Add(head);
            head = new ColumnHeader();
            head.Name = "type";
            head.Text = LanguageManager.StringManager["ColumnHeader_Type"];
            head.Width = (int)(this.columnView.Width * 0.1);
            this.columnView.Columns.Add(head);
            head = new ColumnHeader();
            head.Name = "privateName";
            head.Text = LanguageManager.StringManager["ColumnHeader_PrivateName"];
            head.Width = (int)(this.columnView.Width * 0.2);
            this.columnView.Columns.Add(head);
            head = new ColumnHeader();
            head.Name = "PublicName";
            head.Text = LanguageManager.StringManager["ColumnHeader_PublicName"];
            head.Width = (int)(this.columnView.Width * 0.2);
            this.columnView.Columns.Add(head);
            this.columnView.GridLines = true;
        }

        private void InitTableView()
        {
            this.tableView.Nodes.Clear();
            this.tableView.Nodes.Add(LanguageManager.StringManager["TableView_DefaultString"]);
        }

        private void InitButtonState()
        {
            this.saveToolStripMenuItem.Enabled = false;
            this.saveAllToolStripMenuItem.Enabled = false;
            this.connectToolStripMenuItem.Enabled = true;
            this.breakOffToolStripMenuItem.Enabled = false;
            this.toolbar_connect.Enabled = true;
            this.toolbar_breakoff.Enabled = false;
            this.toolbar_save.Enabled = false;
            this.toolbar_saveall.Enabled = false;
        }

        private void MainForm_Exit(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose(true);
        }

        private void MainForm_Save(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveDlg = new SaveFileDialog();
                saveDlg.Filter = LanguageManager.StringManager["Create_SaveFilter"];
                if (saveDlg.ShowDialog(this) == DialogResult.OK)
                {
                    this.path = saveDlg.FileName;
                    this.CreateFile();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, LanguageManager.StringManager["Error_System_Title"], MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MainForm_SaveAll(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.Description = LanguageManager.StringManager["Create_Msg_ChooseFolder"];
                if (fbd.ShowDialog(this) == DialogResult.OK)
                {
                    this.codeCreater.NameRunner = this.nameRunner;
                    this.codeCreater.DataAdapter = this.dataAdapter;
                    this.codeCreater.Init();
                    this.progressForm.Text = LanguageManager.StringManager["Create_Msg_Text"];
                    this.progressForm.Title = LanguageManager.StringManager["Create_Msg_Title"];
                    this.progressForm.ProgressTotal = 100;
                    this.progressForm.ProgressCurrent = 0;
                    this.path = fbd.SelectedPath;
                    this.createThread = new Thread(this.CreateFilesOnThread);
                    this.createThread.IsBackground = true;
                    this.createThread.Start();
                    this.progressForm.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, LanguageManager.StringManager["Error_System_Title"], MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MainForm_Connect(object sender, EventArgs e)
        {
            this.connectForm.ShowDialog(this);
            if (this.connectForm.ConnectOK)
            {
                this.dataAdapter = this.connectForm.DataAdapter;
                this.tableList = this.dataAdapter.GetTableList();
                this.BindTableList();
                this.connectToolStripMenuItem.Enabled = false;
                this.breakOffToolStripMenuItem.Enabled = true;
                this.toolbar_connect.Enabled = false;
                this.toolbar_breakoff.Enabled = true;
                this.saveAllToolStripMenuItem.Enabled = true;
                this.toolbar_saveall.Enabled = true;
            }
            else
            {
                this.connectToolStripMenuItem.Enabled = true;
                this.breakOffToolStripMenuItem.Enabled = false;
                this.toolbar_connect.Enabled = true;
                this.toolbar_breakoff.Enabled = false;
                this.saveAllToolStripMenuItem.Enabled = false;
                this.toolbar_saveall.Enabled = false;
                this.tableList = null;
            }
        }

        private void MainForm_BreakOff(object sender, EventArgs e)
        {
            this.connectToolStripMenuItem.Enabled = true;
            this.breakOffToolStripMenuItem.Enabled = false;
            this.toolbar_connect.Enabled = true;
            this.toolbar_breakoff.Enabled = false;
            this.saveAllToolStripMenuItem.Enabled = false;
            this.toolbar_saveall.Enabled = false;
            this.tableList = null;
            this.InitTableView();
            this.columnView.Items.Clear();
        }

        private void MainForm_CreateSetting(object sender, EventArgs e)
        {
            this.createSettingForm.ShowDialog(this);
        }

        private void MainForm_SystemSetting(object sender, EventArgs e)
        {
            this.systemSettingForm.ShowDialog(this);
        }

        private void MainForm_LanguageSetting(object sender, EventArgs e)
        {
            this.languageForm.ShowDialog(this);
        }

        private void MainForm_Help(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = LanguageManager.StringManager["Help_File"];
                p.StartInfo.UseShellExecute = true;
                p.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, LanguageManager.StringManager["Error_System_Title"], MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MainForm_Online(object sender, EventArgs e)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = System.Environment.SystemDirectory.Replace("system32", string.Empty) + "Explorer.exe ";
            p.StartInfo.UseShellExecute = true;
            p.StartInfo.Arguments = "http://www.leven.com.cn";
            p.Start();
        }

        private void MainForm_PublicPage(object sender, EventArgs e)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = System.Environment.SystemDirectory.Replace("system32", string.Empty) + "Explorer.exe ";
            p.StartInfo.UseShellExecute = true;
            p.StartInfo.Arguments = "http://blog.leven.com.cn";
            p.Start();
        }

        private void MainForm_About(object sender, EventArgs e)
        {
            this.aboutForm.ShowDialog(this);
        }

        private void MainForm_SelectTable(object sender, EventArgs e)
        {
            if (this.tableView.SelectedNode.Parent != null)
            {
                try
                {
                    this.BindColumnList(this.dataAdapter.GetColumnList(this.tableView.SelectedNode.Text));
                    this.saveToolStripMenuItem.Enabled = true;
                    this.toolbar_save.Enabled = true;
                }
                catch (Exception ex)
                {
                    this.ShowErr(LanguageManager.StringManager["Error_System_Title"], ex.Message);
                }
            }
            else
            {
                this.saveToolStripMenuItem.Enabled = false;
                this.toolbar_save.Enabled = false;
            }
        }

        private void BindTableList()
        {
            try
            {
                this.tableView.Nodes.Clear();
                TreeNode node;
                List<TreeNode> nodeList = new List<TreeNode>();
                foreach (string s in tableList)
                {
                    node = new TreeNode(s);
                    node.Name = s;
                    nodeList.Add(node);
                }
                TreeNode rootNode = new TreeNode(LanguageManager.StringManager["TableView_Now"], nodeList.ToArray());
                this.tableView.Nodes.Add(rootNode);
                this.tableView.SelectedNode = rootNode;
            }
            catch (Exception ex)
            {
                this.ShowErr("System Error.", ex.Message);
            }
        }

        private void BindColumnList(List<ColumnInfo> columnList)
        {
            //this.progressForm = new ProgressForm();
            this.progressForm.Text = LanguageManager.StringManager["ProgressForm_Column_Text"];
            this.progressForm.Title = LanguageManager.StringManager["ProgressForm_Column_Title"];
            this.progressForm.Message = string.Empty;
            this.progressForm.Runner += this.BindColumnListMethod;
            this.progressForm.Data = columnList;
            this.progressForm.ProgressCurrent = 0;
            this.progressForm.Show(this);
            this.progressForm.StartRun(null, null);
            this.progressForm.Runner -= this.BindColumnListMethod;
        }

        private void BindColumnListMethod(object sender, EventArgs e)
        {
            this.columnView.Items.Clear();
            ListViewItem item;
            RunnerMethod tableNameRunner = this.nameRunner.CreateMethod("CreateTableName");
            RunnerMethod attributeNameRunner = this.nameRunner.CreateMethod("CreateAttributeName");
            ProgressForm form = sender as ProgressForm;
            List<ColumnInfo> columnList = form.Data as List<ColumnInfo>;
            form.ProgressTotal = columnList.Count;
            foreach (ColumnInfo info in columnList)
            {
                item = new ListViewItem();
                item.Text = info.Name;
                item.Name = info.Name;
                item.SubItems.Add(info.Type);
                item.SubItems.Add(info.CodeType.Name);
                item.SubItems.Add(Convert.ToString(tableNameRunner.Run(new object[] { info.Name })));
                item.SubItems.Add(Convert.ToString(attributeNameRunner.Run(new object[] { info.Name })));
                this.columnView.Items.Add(item);
                form.ProgressCurrent++;
            }
        }

        private void ShowErr(string title, string message)
        {
            MessageBox.Show(this, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void CreateFile()
        {
            if (string.IsNullOrEmpty(this.path))
            {
                this.ShowErr(LanguageManager.StringManager["Error_System_Title"], LanguageManager.StringManager["Create_Msg_PathNull"]);
                return;
            }
            try
            {
                this.codeCreater.NameRunner = this.nameRunner;
                this.codeCreater.DataAdapter = this.dataAdapter;
                this.codeCreater.Init();
                this.progressForm.Text = LanguageManager.StringManager["Create_Msg_Text"];
                this.progressForm.Title = LanguageManager.StringManager["Create_Msg_Title"];
                this.progressForm.ProgressTotal = 100;
                this.progressForm.ProgressCurrent = 0;
            }
            catch (Exception ex)
            {
                this.ShowErr(LanguageManager.StringManager["Error_System_Title"], ex.Message);
            }
            this.createThread = new Thread(this.CreateFileOnThread);
            this.createThread.IsBackground = true;
            this.createThread.Start();
            this.progressForm.ShowDialog(this);
        }

        private void CreateFileOnThread()
        {
            try
            {
                if (!string.IsNullOrEmpty(this.tableView.SelectedNode.Text))
                {
                    this.codeCreater.Create(this.tableView.SelectedNode.Text);
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(this.path);
                    sw.Write(this.codeCreater.Text);
                    sw.Close();
                    MessageBox.Show(this, LanguageManager.StringManager["Create_Msg_Save"], LanguageManager.StringManager["Message_System_Title"], MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.progressForm.Hide();
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                this.ShowErr(LanguageManager.StringManager["Error_System_Title"], ex.Message);
            }
        }

        public void CreateFilesOnThread()
        {
            try
            {
                this.codeCreater.CreateAllCode();
                MessageBox.Show(this, LanguageManager.StringManager["Create_Msg_Save"], LanguageManager.StringManager["Message_System_Title"], MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.progressForm.Hide();

            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                this.ShowErr(LanguageManager.StringManager["Error_System_Title"], ex.Message);
            }
        }

        public void OnFinishOneTable(string codeString, string table)
        {
            try
            {
                //throw new Exception("The method or operation is not implemented.");
                System.IO.StreamWriter sw = new System.IO.StreamWriter(this.path + "\\" + table + ".cs", false);
                sw.Write(codeString);
                sw.Close();
            }
            catch (Exception ex)
            {
                this.ShowErr(LanguageManager.StringManager["Error_System_Title"], ex.Message);
            }
        }
    }
}